import 'dart:async';
import 'package:flutter/material.dart';
import 'package:rxdart/rxdart.dart';

class CounterPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _CounterPageState();
  }
}

class _CounterPageState extends State<CounterPage> {
  int _counter = 0;
//  final StreamController<int> _streamController = StreamController<int>();
  var _subject = BehaviorSubject<int>();
  @override
  void dispose() {
//    _streamController.close();
    _subject.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Stream version of the Counter App')),
        body: Center(
          child: StreamBuilder(
//              stream: _streamController.stream,
              stream: _subject.stream,
              initialData: _counter,
              builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                return Text('You hit me: ${snapshot.data} times');
              }),
        ),
        floatingActionButton: FloatingActionButton(
          child: const Icon(Icons.add),
          onPressed: () {
            // 每次点击按钮，更加_counter的值，同时通过Sink将它发送给Stream；
            // 每注入一个值，都会引起StreamBuilder的监听，StreamBuilder重建并刷新counter
//            _streamController.sink.add(++_counter);
            _subject.add(++_counter);
            print(context.size);
          },
        ));
  }
}
